<!-- 商品管理 -->
<template>
  <PageContainer title="商品管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-input v-model="searchForm.keyword" placeholder="请输入商品名称/编号搜索" prefix-icon="el-icon-search"
            class="search-input"></el-input>
        </el-col>
        <el-col :span="8" class="operate-buttons">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加商品
          </el-button>
          <el-button type="success" @click="handleExport">
            <i class="el-icon-download"></i> 导出数据
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 商品表格 -->
    <el-table :data="productList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;">
      <el-table-column label="商品ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="商品图片" width="100" align="center">
        <template #default="scope">
          <el-image :src="scope.row.image" :preview-src-list="[scope.row.image]"
            style="width: 50px; height: 50px; object-fit: cover;" fit="cover"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" width="200"></el-table-column>
      <el-table-column label="商品分类" prop="categoryName" width="120" align="center"></el-table-column>
      <el-table-column label="价格" prop="price" width="100" align="center">
        <template #default="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="stock" width="100" align="center"></el-table-column>
      <el-table-column label="状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" align="center"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" :style="{ color: scope.row.status === 1 ? 'red' : 'green' }"
            @click="handleStatusChange(scope.row)">
            {{ scope.row.status === 1 ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="total" :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px; text-align: right;"></TablePagination>

    <!-- 添加/编辑商品弹窗 -->
    <el-dialog :title="isEdit ? '编辑商品' : '添加商品'" :visible.sync="dialogVisible" width="600px"
      :before-close="handleDialogClose">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品分类">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="form.price" type="number" placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input v-model="form.stock" type="number" placeholder="请输入商品库存"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload" :file-list="fileList" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="5" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="上架"
            inactive-text="下架"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import { getProductList, getCategoryList, addProduct, editProduct, updateProductStatus } from '@/api/product'

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 表格数据
const productList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)

// 分类列表
const categoryList = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const fileList = ref([])
const uploadUrl = import.meta.env.VITE_UPLOAD_URL || '/api/upload'

// 表单数据
const form = reactive({
  id: '',
  name: '',
  categoryId: '',
  price: '',
  stock: '',
  image: '',
  description: '',
  status: 1
})

// 表单校验规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { max: 50, message: '商品名称不能超过50个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ]
})

// 获取商品列表
const fetchProductList = async () => {
  try {
    loading.value = true
    const res = await getProductList({
      keyword: searchForm.keyword,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      merchantId: localStorage.getItem('merchantId') // 商家只能查看自己的商品
    })
    productList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const res = await getCategoryList()
    categoryList.value = res.data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchProductList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchProductList()
}

// 添加商品
const handleAdd = () => {
  isEdit.value = false
  // 重置表单
  form.id = ''
  form.name = ''
  form.categoryId = ''
  form.price = ''
  form.stock = ''
  form.image = ''
  form.description = ''
  form.status = 1
  fileList.value = []
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  isEdit.value = true
  // 填充表单
  form.id = row.id
  form.name = row.name
  form.categoryId = row.categoryId
  form.price = row.price
  form.stock = row.stock
  form.image = row.image
  form.description = row.description
  form.status = row.status
  // 图片列表
  fileList.value = row.image ? [{ url: row.image }] : []
  dialogVisible.value = true
}

// 改变商品状态
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '下架' : '上架'}该商品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await updateProductStatus({
      id: row.id,
      status: row.status === 1 ? 0 : 1
    })
    ElMessage.success(`商品${row.status === 1 ? '下架' : '上架'}成功`)
    fetchProductList()
  } catch (error) {
    ElMessage.error(`商品${row.status === 1 ? '下架' : '上架'}失败`)
  }
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate()
    if (isEdit) {
      // 编辑商品
      await editProduct(form)
      ElMessage.success('编辑商品成功')
    } else {
      // 添加商品
      await addProduct({
        ...form,
        merchantId: localStorage.getItem('merchantId')
      })
      ElMessage.success('添加商品成功')
    }
    dialogVisible.value = false
    fetchProductList()
  } catch (error) {
    ElMessage.error(isEdit ? '编辑商品失败' : '添加商品失败')
  }
}

// 上传图片成功
const handleUploadSuccess = (response) => {
  form.image = response.data.url
  fileList.value = [{ url: response.data.url }]
}

// 上传图片前校验
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}

// 关闭弹窗
const handleDialogClose = () => {
  formRef.value.resetFields()
  fileList.value = []
  dialogVisible.value = false
}

// 导出数据
const handleExport = () => {
  // 实际项目中实现导出逻辑
  ElMessage.success('导出成功')
}

// 页面挂载时获取数据
onMounted(() => {
  fetchProductList()
  fetchCategoryList()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .search-input {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>